// UniversalAdmin.Infrastructure/Data/Seed/DataSeeder.cs
using UniversalAdmin.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using UniversalAdmin.Domain.Enums;

namespace UniversalAdmin.Infrastructure.Data.Seed;

public static class DataSeeder
{
  public static async Task SeedAsync(UniversalAdminDbContext context)
  {
    await SeedRoles(context);
    await SeedMenus(context);
    await SeedUsers(context);
    await SeedUserRoles(context);
    await SeedSystemConfigs(context);
    await SeedArticleCategories(context);
  }

  private static async Task SeedArticleCategories(UniversalAdminDbContext context)
  {
    if (await context.ArticleCategories.AnyAsync()) return;

    var categories = new List<ArticleCategory>
    {
        ArticleCategory.Create("通用后台", "关于通用后台的介绍", parentId: null, sort: 1),
        ArticleCategory.Create("技术分享", "技术相关文章", parentId: null, sort: 2),
        ArticleCategory.Create("系统公告", "系统更新与公告", parentId: null, sort: 3),
        ArticleCategory.Create("故障排查", "常见错误码、日志解读、应急处理步骤及根因分析", parentId: null, sort: 4),
        ArticleCategory.Create("社区精选", "用户投稿、第三方扩展、优质问答汇总", parentId: null, sort: 5)
    };
    await context.ArticleCategories.AddRangeAsync(categories);
    await context.SaveChangesAsync();
  }

  private static async Task SeedRoles(UniversalAdminDbContext context)
  {
    if (await context.Roles.AnyAsync()) return;

    var roles = new List<Role>
    {
      Role.Create("SuperAdmin", "超级管理员，拥有所有权限"),
      Role.Create("Admin", "管理员，拥有大部分管理权限"),
      Role.Create("User", "普通用户，只有基本权限")
    };

    await context.Roles.AddRangeAsync(roles);
    await context.SaveChangesAsync();
  }

  private static async Task SeedArticles(UniversalAdminDbContext context)
  {
    if (await context.Roles.AnyAsync()) return;

    var articles = new List<Article>
    {
      //故障排查
      Article.Create("【故障排查】接口 502/504 高频原因与 5 分钟定位手册",
      @"现象：Nginx 返回 502 Bad Gateway 或 504 Gateway Timeout。

      高频根因：
      1. 上游服务崩溃或端口未监听。
      2. upstream_keepalive 连接池耗尽。
      3. 容器健康检查失败导致 Pod 不断重启。

      5 分钟定位步骤：
      1. 看 Nginx error.log
         tail -n 200 /var/log/nginx/error.log | grep -E '502|504'

      2. 看上游服务存活
         curl -I http://127.0.0.1:8080/health

      3. 看容器重启次数
         kubectl get pod -l app=my-api -o wide | awk '{print $4}'

      修复后记得压测验证，并给 Nginx 增加 proxy_connect_timeout 3s; 等兜底参数。",
      "用 3 条命令在 5 分钟内定位 502/504 的根因，附常见修复方案。",
      1,ArticleStatus.Published,4
      ),
      //技术分享
      Article.Create( ".NET 8 中新增的 “Keyed Services” 实战：一行代码替换工厂模式",
      @".NET 8 在 DI 容器中引入了 KeyedService，让我们可以用 Key 注册/解析服务，彻底告别繁琐的工厂。
      
      1. 注册
      builder.Services.AddKeyedSingleton<IEmailSender, SmtpSender>(""smtp"");
      builder.Services.AddKeyedSingleton<IEmailSender, ApiSender>(""api"");

      2. 解析
      public OrderService([FromKeyedServices(""smtp"")] IEmailSender sender) { }

      3. 运行时动态切换
      var sender = provider.GetRequiredKeyedService<IEmailSender>(config.Provider);

      性能测试表明，相比传统工厂，内存分配减少 18%，首次解析耗时降低 34%。",
      "通过 .NET 8 Keyed Services 简化多实现服务注入，附性能对比数据。",
      1,
      ArticleStatus.Published,
      2
      )
    };

    await context.Articles.AddRangeAsync(articles);
    await context.SaveChangesAsync();
  }

  private static async Task SeedMenus(UniversalAdminDbContext context)
  {
    if (await context.Menus.AnyAsync()) return;

    // 用工厂方法创建
    var menus = new List<Menu>
    {
        Menu.Create("仪表盘",  "/dashboard", "Odometer", parentId: null, sort: 1),
        Menu.Create("用户管理", "/users",       "User",      parentId: null, sort: 2),
        Menu.Create("用户列表", "/users/list",  "List",      parentId: 2,    sort: 1),
        Menu.Create("添加用户", "/users/add",   "Plus",      parentId: 2,    sort: 2),
        Menu.Create("角色管理", "/roles",   "Lock",      parentId: null,    sort: 3),
        Menu.Create("角色列表", "/roles/list",   "List",      parentId: 5,    sort: 1),
        Menu.Create("角色添加", "/roles/add",   "Plus",      parentId: 5,    sort: 2),
        Menu.Create("菜单管理", "/menus",   "Menu",      parentId: null,    sort: 4),
        Menu.Create("菜单列表", "/menus/list",   "List",      parentId: 8,    sort: 1),
        Menu.Create("添加菜单", "/menus/add",   "Plus",      parentId: 8,    sort: 2),
        Menu.Create("系统设置", "/system",   "Setting",      parentId: null,    sort: 5),
        Menu.Create("系统配置", "/system/config",   "Setting",      parentId: 11,    sort: 1),
        Menu.Create("日志管理", "/logs",   "Document",      parentId: null,    sort: 6),
        Menu.Create("操作日志", "/logs/operation",   "Document",      parentId: 13,    sort: 1),
        Menu.Create("内容管理", "/content",   "Document",      parentId: null,    sort: 7),
        Menu.Create("文章管理", "/content/articles",   "Document",      parentId: 15,    sort: 1),
        Menu.Create("文件管理", "/content/files",   "Lock",      parentId: 15,    sort: 2),
    };

    await context.Menus.AddRangeAsync(menus);
    await context.SaveChangesAsync();
  }

  private static async Task SeedUsers(UniversalAdminDbContext context)
  {
    if (await context.Users.AnyAsync()) return;

    var adminUser = new User
    {
      Id = 1,
      Username = "superAdmin",
      Password = "$2a$12$YlXJlEk3a36wHokcwJdX4uoVeW19JuTedL3V2aFciMcEvEV2OvDjG", // admin123
      Email = "superAdmin@example.com",
      IsActive = true
    };

    var admin = new User
    {
      Id = 2,
      Username = "admin",
      Password = "$2a$12$YlXJlEk3a36wHokcwJdX4uoVeW19JuTedL3V2aFciMcEvEV2OvDjG", // admin123
      Email = "admin@example.com",
      IsActive = true
    };

    var user = new User
    {
      Id = 3,
      Username = "user",
      Password = "$2a$12$YlXJlEk3a36wHokcwJdX4uoVeW19JuTedL3V2aFciMcEvEV2OvDjG", // admin123
      Email = "user@example.com",
      IsActive = true
    };

    await context.Users.AddAsync(adminUser);
    await context.Users.AddAsync(admin);
    await context.Users.AddAsync(user);

    await context.SaveChangesAsync();
  }

  private static async Task SeedUserRoles(UniversalAdminDbContext context)
  {
    if (await context.UserRoles.AnyAsync()) return;

    var userRoles = new List<UserRole>
        {
            new() { UserId = 1, RoleId = 1 }, // admin用户拥有SuperAdmin角色
            new() { UserId = 2, RoleId = 2 },
            new() { UserId = 3, RoleId = 3 }
        };

    await context.UserRoles.AddRangeAsync(userRoles);
    await context.SaveChangesAsync();
  }

  private static async Task SeedSystemConfigs(UniversalAdminDbContext context)
  {
    var requiredConfigs = new List<(string Key, string Value, string Description)>
    {
        ("site_name", "通用后台管理系统", "网站名称"),
        ("site_title", "通用后台管理系统 - 高效、安全、易用", "网站标题"),
        ("site_description", "一个基于Vue3和.NET8构建的现代化后台管理系统", "网站描述"),
        ("site_keywords", "后台管理,Vue3,.NET8,权限管理", "网站关键词"),
        ("site_logo", "", "网站Logo"),
        ("copyright", "© 2024 通用后台管理系统. All rights reserved.", "版权信息")
    };

    foreach (var (key, value, description) in requiredConfigs)
    {
      var existingConfig = await context.SystemConfigs.FirstOrDefaultAsync(c => c.Key == key);
      if (existingConfig == null)
      {
        var config = new SystemConfig
        {
          Key = key,
          Value = value,
          Description = description,
          CreatedAt = DateTime.UtcNow,
          UpdatedAt = DateTime.UtcNow
        };
        await context.SystemConfigs.AddAsync(config);
      }
    }

    await context.SaveChangesAsync();
  }
}